package com.hub.service.asset.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.util.StringUtil;
import com.hub.service.impl.BaseServiceImpl;
import com.hub.dto.asset.SearchAssetBrandDto;
import com.hub.dto.asset.BrandInfoDto;
import com.hub.frame.consts.ConstantUtil;
import com.hub.utils.KeyValueModel;
import com.hub.entity.asset.AssetBrandInfo;
import com.hub.utils.enums.BrandGradeEnum;
import com.hub.mapper.asset.BrandInfoMapper;
import com.hub.model.asset.BrandModel;
import com.hub.service.asset.IAssetBrandInfoService;
import com.hub.utils.ApiCodeEnum;
import com.hub.utils.ApiResultObject;
import com.hub.utils.PagingResultObject;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 品牌信息表 服务实现类
 * </p>
 *
 * @author hub
 * @since 2020-05-12
 */
@Service
public class AssetBrandInfoServiceImpl extends BaseServiceImpl<BrandInfoMapper, AssetBrandInfo> implements IAssetBrandInfoService {

    @Autowired
    private BrandInfoMapper brandInfoMapper;

    @Autowired
    private Mapper mapper;

    /**
     * 
     * 分页查询品牌
     * @param queryModel
     * @return
     */
    @Override
    public PagingResultObject getList(SearchAssetBrandDto queryModel) {
        queryModel.setPageIndex( queryModel.getPageIndex() > 0 ? queryModel.getPageIndex() : 1);
        queryModel.setPageSize(queryModel.getPageSize() > 0?queryModel.getPageSize():20);
        //查询条件
        QueryWrapper wrapper = new QueryWrapper();
        if(StringUtil.isNotEmpty(queryModel.getBrandCode())){
            wrapper.like("brand_code",queryModel.getBrandCode());
        }
        if(StringUtil.isNotEmpty(queryModel.getBrandName())){
            wrapper.like("brand_name",queryModel.getBrandName());
        }
        if(StringUtil.isNotEmpty(queryModel.getBrandEngName())){
            wrapper.like("brand_eng_name",queryModel.getBrandEngName());
        }
        wrapper.eq("active_flg", ConstantUtil.YES);
        IPage<AssetBrandInfo> result = baseMapper.selectPage(new Page<>(queryModel.getPageIndex(), queryModel.getPageSize()),wrapper);
        List<BrandModel> modelList = new ArrayList<>();
        for(AssetBrandInfo entity : result.getRecords()){
            BrandModel model = mapper.map(entity,BrandModel.class);
            model.setGradesStr(BrandGradeEnum.getDescription(entity.getGrades()));
            modelList.add(model);
        }
        return PagingResultObject.success(modelList,queryModel.getPageIndex(),queryModel.getPageSize(),result.getTotal());
    }

    /**
     * 
     * 详情
     * @param brandId
     * @return
     */
    @Override
    public ApiResultObject<BrandModel> getBrandDetail(int brandId){
        //查询详情
        AssetBrandInfo brandDetail = brandInfoMapper.getAssetBrandDetail(brandId);
        if(null != brandDetail){
            BrandModel resultBrand = mapper.map(brandDetail, BrandModel.class);
            return ApiResultObject.success(ApiCodeEnum.SUCCESS.getCode(),"查询成功！",resultBrand);
        }
        return ApiResultObject.failed(ApiCodeEnum.FAILED.getCode(),"详情查询失败");
    };

    /**
     * 
     * 自动生成编号
     * @return
     */
    private String autoGenerateBrandCode(){
        //获取当前总数
        long total = brandInfoMapper.allBrandCount();
        //生成新的编号，规则为brand+当前数量+1
        String newCode = "brand-" + String.format("%03d",total+1);
        return newCode;
    }

    /**
     * 
     * 新增品牌
     * @param addModel
     * @return
     */
    @Override
    @Transactional
    public ApiResultObject doAddAssetBrand(BrandInfoDto addModel){
        //验证品牌名或英文名是否存在
        QueryWrapper<AssetBrandInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_name",addModel.getBrandName()).or().eq("brand_eng_name",addModel.getBrandEngName());
        wrapper.eq("active_flg", ConstantUtil.YES);
        if(this.count(wrapper) > 0){
            return ApiResultObject.failed("品牌名或英文名已存在，无法保存,请重新输入！");
        }
        AssetBrandInfo entity = mapper.map(addModel, AssetBrandInfo.class);
        //有效性，默认为有效
//        entity.setActiveFlg(ActiveFlgEnum.Effective.getCode());
        //获取当前时间，时间戳格式
//        Date nowDate = new Date();
        //创建时间
//        entity.setCreateTime(nowDate);
//        //创建人
//        entity.setCreateUser(AppContextHolder.getUserName());
//        //最后更新时间
//        entity.setModifyTime(nowDate);
//        //最后更新人
//        entity.setModifyUser(AppContextHolder.getUserName());
        //自动生成编号
//        entity.setBrandCode(this.autoGenerateBrandCode());
        //新增品牌
//        int flag = brandInfoMapper.doAddAssetBrand(entity);
        if(this.save(entity)){
            return  ApiResultObject.success(ApiCodeEnum.SUCCESS.getCode(),"添加成功！");
        }
        return ApiResultObject.failed(ApiCodeEnum.FAILED.getCode(),"添加失败！");
    };

    /**
     * 
     * 删除品牌
     * @param brandId
     * @return
     */
    @Override
    @Transactional
    public ApiResultObject doDeleteAssetBrand(Long brandId){
        AssetBrandInfo deleteModel = new AssetBrandInfo();
//        deleteModel.setId(brandId);
        //有效性，改为无效
//        deleteModel.setActiveFlg(ActiveFlgEnum.Invalid.getCode());
        //最后更新时间
//        deleteModel.setModifyTime(new Date());
        //最后修改人
//        deleteModel.setModifyUser(AppContextHolder.getUserName());
//        int flag = brandInfoMapper.doDeleteAssetBrand(deleteModel);
        if(brandId < 0){
            return ApiResultObject.failed(ApiCodeEnum.FAILED.getCode(),"参数异常: 资产信息ID异常!");
        }
        if(this.removeById(brandId)){
            return ApiResultObject.success(ApiCodeEnum.SUCCESS.getCode(),"删除成功！");
        }
        return ApiResultObject.failed(ApiCodeEnum.FAILED.getCode(),"删除失败！");
    };

    /**
     * 
     * 修改品牌
     * @param modifyModel
     * @return
     */
    @Override
    @Transactional
    public ApiResultObject doModifyAssetBrand(BrandInfoDto modifyModel){
        //验证品牌名或英文名是否已存在
        int nameFlg = brandInfoMapper.verifyExistenceNameOrEngName(modifyModel);
        if(nameFlg > 0){
            return ApiResultObject.failed(ApiCodeEnum.FAILED.getCode(),"该品牌名称或英文名已存在！！");
        }
        //验证品牌名或英文名是否存在
        QueryWrapper<AssetBrandInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_name",modifyModel.getBrandName()).or().eq("brand_eng_name",modifyModel.getBrandEngName());
        wrapper.ne("id",modifyModel.getId());
        wrapper.eq("active_flg", ConstantUtil.YES);
        if(this.count(wrapper) > 0){
            return ApiResultObject.failed("品牌名或英文名已存在，无法保存,请重新输入！");
        }
        AssetBrandInfo entity = mapper.map(modifyModel, AssetBrandInfo.class);
        //最后更新时间
//        entity.setModifyTime(new Date());
        //最后更新人
//        entity.setModifyUser(AppContextHolder.getUserName());
        //修改品牌
//        long flag = brandInfoMapper.doModifyAssetBrand(entity);
        if( this.updateById(entity) ){
            return ApiResultObject.success(ApiCodeEnum.SUCCESS.getCode(),"修改成功！");
        }
        return ApiResultObject.failed(ApiCodeEnum.FAILED.getCode(),"修改失败！");
    };


    /**
     * 获取品牌下来列表数据源
     * @return
     */
    public ApiResultObject getBrandKeyValues() {
//        QueryWrapper<BrandInfoEntity> wrapper = new QueryWrapper<>();
//        wrapper.eq("active_flg", ConstantUtil.YES);
//        List<BrandInfoEntity> list = baseMapper.selectList(wrapper);

        List<AssetBrandInfo> list = brandInfoMapper.allBrands();
        List<KeyValueModel> result = new ArrayList<KeyValueModel>();

        for (AssetBrandInfo entity:list
             ) {
            KeyValueModel model = new KeyValueModel();
            model.setKey(entity.getId());
            model.setValue(entity.getBrandName());

            result.add(model);
        }

        return ApiResultObject.success(result);
    }
}
